import os.path
from openpyxl import load_workbook
from pathlib import Path
import json
from colorama import Fore, Back, Style
import pandas as pd
from collections import defaultdict


class FileHandle:
    def __init__(self):
        self.sub_fun_dict = {}
        self.col_sub_fun_index = -1
        self.col_usr_case_index = -1
        self.col_result_index = -1
        pass

    @staticmethod
    def check_file(file_path):
        path = Path(file_path)

        if not path.exists():
            return False, "文件不存在"
        elif not path.is_file():
            return False, "路径不是文件"
        else:
            return True

        # try:
        #     with open(path, 'r') as f:
        #         pass
        #     return True, "文件存在且可读取"
        # except PermissionError:
        #     return False, "没有读取权限"
        # except Exception as e:
        #     return False, f"访问文件出错: {str(e)}"

    @staticmethod
    def check_file_format(file):
        wb = load_workbook(file)
        sheet_list = wb.get_sheet_names()
        print(sheet_list)
        row_list = []
        sheet_test_case_name = []
        for i in range(len(sheet_list)):
            sheet = wb.get_sheet_by_name(sheet_list[i])
            row_list.clear()
            for row in sheet[1]:
                if row.value is not None:
                    row_list.append(row.value)
            if ('ID' in row_list and 'Requirement ID' in row_list and
                'Priority' in row_list and 'Test Steps.Action' in row_list and
                    'Test Steps.Expected result' in row_list):
                sheet_test_case_name.append(sheet_list[i])
        return sheet_test_case_name

    @staticmethod
    def count_all_data1(in_file):
        # 统计结构：{(id, requirement_id): {'pass': x, 'fail': y, 'blank': z}}
        result_stats = defaultdict(lambda: {'pass': 0, 'fail': 0, 'blank': 0})
        # 读取 Excel 文件（假设文件名为 "data.xlsx"）
        xls = pd.ExcelFile(in_file)
        # 遍历所有 sheet
        for sheet_name in xls.sheet_names:
            df = xls.parse(sheet_name)
            # 确保包含必要的列
            if {'ID', 'Requirement ID', 'Result'}.issubset(df.columns):
                for _, row in df.iloc[1:].iterrows():
                    key = (row['ID'], row['Requirement ID'])
                    result_value = str(row['Result']).strip().lower()

                    if result_value == 'pass':
                        result_stats[key]['pass'] += 1
                    elif result_value == 'fail':
                        result_stats[key]['fail'] += 1
                    elif result_value in ('', 'nan', 'none'):
                        result_stats[key]['blank'] += 1
                    else:
                        result_stats[key]['blank'] += 1  # 其他非标准值视为空白处理

        # 输出统计结果
        for key, counts in result_stats.items():
            print(
                f"ID: {key[0]}, Requirement ID: {key[1]}, Pass: {counts['pass']}, Fail: {counts['fail']}, Blank: {counts['blank']}")
        return result_stats

    def save_to_excel(self, result_stats, out_file):
        self.sub_fun_dict = FileHandle.get_json_dict('sub_fun.json')
        output_data = []
        seen_ids = set()
        for key, counts in result_stats.items():
            id_display = key[0] if key[0] not in seen_ids else ''
            id_name = self.sub_fun_dict.get(key[0], '') if key[0] not in seen_ids else ''
            seen_ids.add(key[0])

            output_data.append({
                'ID': id_display,
                'Name': id_name,
                'Requirement ID': key[1],
                'Pass': counts['pass'],
                'Fail': counts['fail'],
                'Blank': counts['blank']
            })

        output_df = pd.DataFrame(output_data)
        output_df.to_excel(out_file, index=False)

        print("统计结果已导出到当前文件夹" + out_file)

    @staticmethod
    def get_version():
        json_dict = FileHandle.get_json_dict("info.json")
        return json_dict['version']

    @staticmethod
    def get_json_dict(filename):
        file_path = os.getcwd() + os.sep + 'resource' + os.sep + filename
        if not os.path.exists(file_path):
            print(Fore.RED + filename + " is not exit!!!")
            print(Style.RESET_ALL)
            return
        with open(file_path, 'r', encoding='utf-8-sig') as f:
            json_dict = json.load(f)
            return json_dict



